package znbkSameQuesTranslate.SQ_TLTK;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.AnswerViewPagerAdapter;
import com.example.znbk.znbklibrary.base.BaseFragment;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.example.znbk.znbklibrary.voicePlayer.VoicePlayer;
import com.example.znbk.znbklibrary.widget.ScaleButton;
import com.lancoo.znbkxx.R;

import java.util.ArrayList;
import java.util.List;

import znbkBkfx.AboutCountDowm.CountDownView;
import znbkSameQuesTranslate.GetSameQuesJson.SameQuesPaperEntity;

@SuppressLint("ValidFragment")
public class SQxlTltkFragment extends BaseFragment {

    private String AudioPath = "";
    private void getEntityInfor(){
        AudioPath = sameQuesPaperEntity.get(childIndex).getQuesFromTK().getAudioList().get(0).getPath();
    }

    private List<SameQuesPaperEntity> sameQuesPaperEntity;
    private int childIndex = -1;
    private CallBackFragmentTltk callBackFragmentTltk;
    public SQxlTltkFragment( List<SameQuesPaperEntity> sameQuesPaperEntity, final int childIndex, CallBackFragmentTltk callBackFragmentTltk){
        this.sameQuesPaperEntity = sameQuesPaperEntity;
        this.childIndex = childIndex;
        this.callBackFragmentTltk = callBackFragmentTltk;
        getEntityInfor();
    }

    @Override
    protected int createLayout() {
        return R.layout.cntxl_fragment_tltk;
    }

    private ImageButton mIBtnPlayPause;//音频控制按钮
    private SeekBar mSbMusicProgress;//音频进度条
    private TextView mTvMusicTime;//播放时间点
    private WebView mWvQuesBody;

    private ViewPager mVpAnswer;
    private ArrayList<View> list;
    public AnswerViewPagerAdapter mAnswerViewPagerAdapter;

    private RelativeLayout mRlMyBrowseBg;
    private CountDownView mCdvMyBrowse;

    public boolean isVoicePlayingEnd = false;
    private RelativeLayout mRlControlView;
    private ScaleButton mSBtnSubmit;

    @Override
    protected void initView(View view) {
        //显示播放器
        mIBtnPlayPause = view.findViewById(R.id.ibtn_audioIcon);
        mSbMusicProgress = view.findViewById(R.id.sb_musicProgress);
        mTvMusicTime = view.findViewById(R.id.tv_musicTime);
        mWvQuesBody = view.findViewById(R.id.wv_quesBody);
        mWvQuesBody.setBackgroundColor(0); // 设置背景色
        String QuesBodyAsk  = sameQuesPaperEntity.get(childIndex).getQuesFromTK().getChildList().get(0).
                getSubChildList().get(0).getSubChildAsk();
        mWvQuesBody.loadData(QuesBodyAsk+"</br>", "text/html", "utf-8");

        mVoicePlayer = new VoicePlayer(mSbMusicProgress, AudioPath, mTvMusicTime, mIBtnPlayPause,
                false, true, false, new VoicePlayer.FinishPlay() {
            @Override
            public void onFinishPlay() {
                isVoicePlayingEnd = true;
                //音频播放结束，点亮录音按钮（此处需要刷新界面）
                list = new ArrayList<>();
                list.clear();
                RecyclerView mRvAnswer = new RecyclerView(getActivity());
                mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
                SQxlTltkAnswerAdapter mAnswerAdapter = new SQxlTltkAnswerAdapter(getActivity(),
                        sameQuesPaperEntity,childIndex,isVoicePlayingEnd);
                mAnswerAdapter.setHasStableIds(true);
                mRvAnswer.setAdapter(mAnswerAdapter);
                int ItemSize  = sameQuesPaperEntity.get(childIndex).getQuesFromTK().getTotalItemCount();
                mRvAnswer.setItemViewCacheSize(ItemSize);
                list.add(mRvAnswer);
                mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
                mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
            }
        });
        int SubmitState = sameQuesPaperEntity.get(childIndex).getFavouriteAndNote().getSubmitState();
        if(SubmitState==2){
            mVoicePlayer.setBtnPlayClickAble(true);
        }

        //显示TlxzAnswer内容
        //显示Answer信息
        mVpAnswer = view.findViewById(R.id.vp_answerTltk);
        list = new ArrayList<>();
        list.clear();
        RecyclerView mRvAnswer = new RecyclerView(getActivity());
        mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
        SQxlTltkAnswerAdapter mAnswerAdapter = new SQxlTltkAnswerAdapter(getActivity(),
                sameQuesPaperEntity,childIndex,isVoicePlayingEnd);
        mAnswerAdapter.setHasStableIds(true);
        mRvAnswer.setAdapter(mAnswerAdapter);
        int ItemSize  = sameQuesPaperEntity.get(childIndex).getQuesFromTK().getTotalItemCount();
        mRvAnswer.setItemViewCacheSize(ItemSize);
        list.add(mRvAnswer);
        mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
        mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
        mVpAnswer.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                sameQuesPaperEntity.get(childIndex).getFavouriteAndNote().setCurrentSubChildAnswerIndex(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        //显示浏览倒计时
        mRlMyBrowseBg = view.findViewById(R.id.rl_myBrowseBg);
        mCdvMyBrowse =  view.findViewById(R.id.cdv_myBrowse);
        mCdvMyBrowse.setCountdownTime(5);
        mCdvMyBrowse.setRingWidth(12);
        mCdvMyBrowse.setAddCountDownListener(new CountDownView.OnCountDownFinishListener() {
            @Override
            public void countDownFinished() {
                LancooUtils.showShort(getActivity(),"倒计时结束");
                hideBrowseView();
                play();
                sameQuesPaperEntity.get(childIndex).getFavouriteAndNote().setSubmitState(1);
            }
        });
        mCdvMyBrowse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mCdvMyBrowse.pauseCountDown();

                sameQuesPaperEntity.get(childIndex).getFavouriteAndNote().setSubmitState(1);
                hideBrowseView();//开启隐藏浏览view动画
                play();
            }
        });

        //显示同类题训练按钮
        mRlControlView = view.findViewById(R.id.rl_controlView);
//        mRlSubmitBg = view.findViewById(R.id.rl_submitBg);
        mSBtnSubmit  = view.findViewById(R.id.sbtn_submit);
        mSBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pause();
                sameQuesPaperEntity.get(childIndex).getFavouriteAndNote().setSubmitState(2);
                hideSBtnSubmit();

            }
        });

    }

    @SuppressLint("NewApi")
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        int SubmitState = sameQuesPaperEntity.get(childIndex).getFavouriteAndNote().getSubmitState();

        if(isVisibleToUser){
            Log.e("setUserVisibleHint","================AnswerState===================="+SubmitState);
            if(SubmitState==0) {
                final Handler mH = new Handler();
                mH.post(new Runnable() {
                    @Override
                    public void run() {

                        if(mCdvMyBrowse!=null) {
                            if (mCdvMyBrowse.isCountDownRunning()) {
                                mCdvMyBrowse.resumeCountDown();
                            } else {
                                showBrowseView();
                                mCdvMyBrowse.startCountDown();
                            }
                            mH.removeCallbacks(this);
                        }else{
                            mH.post(this);
                        }

                    }
                });
            }else if(SubmitState==1){
                if(!isVoicePlayingEnd) {
                    play();
                }
            }else if(SubmitState==2){
                pause();
            }

        }else{
            pause();
            if(mCdvMyBrowse!=null) {
                mCdvMyBrowse.pauseCountDown();
            }
        }

    }

    private void showBrowseView(){
        if(mRlMyBrowseBg.getVisibility()==View.GONE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyBrowseBg, View.TRANSLATION_Y, 300f, 0f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    mRlMyBrowseBg.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }
    private void hideBrowseView(){
        if(mRlMyBrowseBg.getVisibility()==View.VISIBLE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyBrowseBg, View.TRANSLATION_Y, 0f, 300f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mRlMyBrowseBg.setVisibility(View.GONE);
                    list = new ArrayList<>();
                    list.clear();
                    RecyclerView mRvAnswer = new RecyclerView(getActivity());
                    mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
                    SQxlTltkAnswerAdapter mAnswerAdapter = new SQxlTltkAnswerAdapter(getActivity(),
                            sameQuesPaperEntity,childIndex,isVoicePlayingEnd);
                    mAnswerAdapter.setHasStableIds(true);
                    mRvAnswer.setAdapter(mAnswerAdapter);
                    int ItemSize  = sameQuesPaperEntity.get(childIndex).getQuesFromTK().getTotalItemCount();
                    mRvAnswer.setItemViewCacheSize(ItemSize);
                    list.add(mRvAnswer);
                    mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
                    mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }


    private void doSubmitRefresh(){
        list.clear();
        RecyclerView mRvAnswer = new RecyclerView(getActivity());
        mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
        SQxlTltkAnswerAdapter mAnswerAdapter = new SQxlTltkAnswerAdapter(getActivity(),
                sameQuesPaperEntity, childIndex,isVoicePlayingEnd);
        mAnswerAdapter.setHasStableIds(true);
        mRvAnswer.setAdapter(mAnswerAdapter);
        int ItemSize  = sameQuesPaperEntity.get(childIndex).getQuesFromTK().getTotalItemCount();
        mRvAnswer.setItemViewCacheSize(ItemSize);
        list.add(mRvAnswer);
        mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
        mVpAnswer.setAdapter(mAnswerViewPagerAdapter);

        callBackFragmentTltk.submitKgtQuesAnswer();
    }


    private void hideSBtnSubmit(){
        ObjectAnimator translationY1 = ObjectAnimator.ofFloat(mRlControlView, View.TRANSLATION_Y, 0f, 300f);
        ObjectAnimator translationY2 = ObjectAnimator.ofFloat(mSBtnSubmit, View.TRANSLATION_Y, 0f, 300f);
        AnimatorSet setShow = new AnimatorSet();
        setShow.playTogether(translationY1,translationY2);
        setShow.setDuration(600);
        setShow.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mRlControlView.setVisibility(View.GONE);
                mSBtnSubmit.setVisibility(View.GONE);
                doSubmitRefresh();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        setShow.start();
    }

    public interface CallBackFragmentTltk {
        void submitKgtQuesAnswer();
    }

}